package com.gwt.client.activity;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.gwt.client.ClientFactory;
import com.gwt.client.event.SlideTransitionEvent;
import com.gwt.client.place.SlidePlace;
import com.gwt.client.ui.Slide;

public class SlideActivity extends AbstractActivity implements Slide.Presenter {

	private ClientFactory clientFactory;
	private SlidePlace place;
	private Slide currentSlide;

	public SlideActivity(SlidePlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
		this.place = place;
	}

	@Override
	public void start(final AcceptsOneWidget panel, EventBus eventBus) {

		final Slide.Presenter presenter = this;
		eventBus.addHandler(SlideTransitionEvent.TYPE, new SlideTransitionEvent.Handler() {

			@Override
			public void gotoSlide(int nextSlide) {
				int slideNumber = 1;
				try {
					slideNumber = Integer.valueOf(place.getName());
				} catch (NumberFormatException e) {
					Window.alert(e.getMessage());
					slideNumber = 1;
				} finally {
					place = new SlidePlace(String.valueOf(slideNumber + nextSlide));
					presenter.goTo(place);
				}
			}

		});

		currentSlide = clientFactory.getSlide(Integer.valueOf(place.getName()));
		currentSlide.setPresenter(this);
		panel.setWidget(currentSlide);

	}

	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
	}

}
